package cc.comac.mom.datahandlers.entity;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.api.lifelimit.LifeLimitPartBaseService;
import cc.comac.mom.bean.BasicStandardRestrictedPart;
import cc.comac.mom.bean.QualityAsrFeaturesBean;
import cc.comac.mom.bean.QualityQarBasicStandard;
import cc.comac.mom.bean.QualityQarBasicStandardAsrFeatures;
import cc.comac.mom.bean.QualityQarBasicStandardCheck;
import cc.comac.mom.bean.QualityQarBasicStandardRequirement;
import cc.comac.mom.bean.QualityQarBasicStandardUpgrade;
import cc.comac.mom.bean.base.LimitPageBean;
import cc.comac.mom.dao.entity.QualityPlanToDoDao;
import cc.comac.mom.dao.entity.QualityQarBasicStandardDao;
import cc.comac.mom.dao.entity.QualityQarBasicStandardUpgradeDao;
import cc.comac.mom.dao.entity.QualitySapPurchaseOrderDao;
import cc.comac.mom.entity.QualityAsrFeaturesEntity;
import cc.comac.mom.entity.QualityPlanToDoEntity;
import cc.comac.mom.entity.QualityQarBasicStandardAsrFeaturesEntity;
import cc.comac.mom.entity.QualityQarBasicStandardCheckEntity;
import cc.comac.mom.entity.QualityQarBasicStandardEntity;
import cc.comac.mom.entity.QualityQarBasicStandardRequirementEntity;
import cc.comac.mom.entity.QualityQarBasicStandardUpgradeEntity;
import cc.comac.mom.entity.QualityQarTaskPendingMessageEntity;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.DataStatus;
import cc.comac.mom.util.MomConstants;
import cc.comac.mom.util.ResultBean;

@Component
@Transactional
public class QualityQarBasicStandardDataHanldler
		extends ServiceImpl<QualityQarBasicStandardDao, QualityQarBasicStandardEntity> {

	@Autowired
	private QarRestrictedPartDataHandler qarRestrictedPartDataHandler;
	@Autowired
	private QualityQarBasicStandardDao qualityQarBasicStandardDao;
	@Autowired
	private QualityQarBasicStandardAsrFeaturesDataHandler qualityQarBasicStandardAsrFeaturesDataHandler;
	@Autowired
	private QualityQarBasicStandardCheckDataHandler qualityQarBasicStandardCheckDataHandler;

	@Autowired
	private QualityQarBasicStandardRequirementDataHandler qualityQarBasicStandardRequirementDataHandler;
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;

	@Autowired
	private QualityQarBasicStandardUpgradeDao qualityQarBasicStandardUpgradeDao;

	@Autowired
	private QualityQarBasicStandardUpgradeDataHandler qualityQarBasicStandardUpgradeDataHandler;

	@Autowired
	private QualityQarTaskPendingMessageDataHandler qualityQarTaskPendingMessageDataHandler;

	@Autowired
	private QualityPlanToDoDao qualityPlanToDoDao;

	@Autowired
	private QualityPlanToDoDataHandler qualityPlanToDoDataHandler;

	@Autowired
	private QualityQarCheckInvoiceDataHandler qualityQarCheckInvoiceDataHandler;

	@Autowired
	private QualitySapPurchaseOrderDao qualitySapPurchaseOrderDao;
	@Autowired
	private LifeLimitPartBaseService lifeLimitPartBaseService;

	@Autowired
	private BasicStandardRestrictedPartDataHandler basicStandardRestrictedPartDataHandler;

	public void validateField(QualityQarBasicStandardEntity qualityQarBasicStandardEntity, boolean flag) {
		QueryWrapper<QualityQarBasicStandardEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("material_number", qualityQarBasicStandardEntity.getMaterialNumber());
		List<QualityQarBasicStandardEntity> selectList = qualityQarBasicStandardDao.selectList(queryWrapper);
		if (selectList != null && selectList.size() > 0) {
			if (qualityQarBasicStandardEntity.getId() == 0 && flag) {
				throw new RuntimeException("数据重复");
			} else if (selectList.get(0).getId() != qualityQarBasicStandardEntity.getId() && flag) {
				throw new RuntimeException("数据重复");
			}
		}
		if (StringUtils.isEmpty(qualityQarBasicStandardEntity.getPartNumber())) {
			throw new RuntimeException("新增材料/零件图号不能为空！");
		}
		if (StringUtils.isEmpty(qualityQarBasicStandardEntity.getPartName())) {
			throw new RuntimeException("新增材料/零件名称不能为空！");
		}
		if (StringUtils.isEmpty(qualityQarBasicStandardEntity.getMaterialNumber())) {
			throw new RuntimeException("新增物料编码不能为空！");
		}
		if (StringUtils.isEmpty(qualityQarBasicStandardEntity.getModel())) {
			throw new RuntimeException("新增型号不能为空！");
		}
		if (StringUtils.isEmpty(qualityQarBasicStandardEntity.getStandard())) {
			throw new RuntimeException("新增规范/标准不能为空！");
		}
		if (StringUtils.isEmpty(qualityQarBasicStandardEntity.getSamplesSize())) {
			throw new RuntimeException("新增要求尺寸不能为空！");
		}
		if (StringUtils.isEmpty(qualityQarBasicStandardEntity.getRequiredSize())) {
			throw new RuntimeException("新增要求尺寸不能为空！");
		}
		if (qualityQarBasicStandardEntity.getSamplesQuantity() == 0) {
			throw new RuntimeException("新增试样数量不能为空！");
		}
	}

	// 校验计划代办中是否存在未处理的母本异常计划
	public void validatePlanToDoIfDeal(String partNo, String partName, String materialNumber, String materialType) {
		QueryWrapper<QualityPlanToDoEntity> queryWrapper = new QueryWrapper<QualityPlanToDoEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("part_no", partNo).eq("material_number", materialNumber);
		queryWrapper.eq("to_do_type", 2);
		queryWrapper.eq("part_name", partName);
		List<QualityPlanToDoEntity> selectList = qualityPlanToDoDao.selectList(queryWrapper);
		if (selectList.size() > 0) {
			for (QualityPlanToDoEntity qualityPlanToDoEntity : selectList) {
				baseEntityDataUtil.updateBaseEntityData(qualityPlanToDoEntity);
				qualityPlanToDoEntity.setStatus(0);
			}
			qualityPlanToDoDataHandler.updateBatchById(selectList, selectList.size());
		}
	}

	// 新增或者提交qar母本按钮
	public ResultBean insertQarBasicStandard(@RequestBody QualityQarBasicStandard qualityQarBasicStandard)
			throws RuntimeException {
		ResultBean resultBean = new ResultBean(true);
		QualityQarBasicStandardEntity innerData = qualityQarBasicStandard.getInnerData();

		List<QualityAsrFeaturesBean> asrFeaturesList = qualityQarBasicStandard.getQarBasicStandardAsrFeaturesList();

		// 将对象数据进行置换，方便保存特征库数据信息
		ArrayList<QualityQarBasicStandardAsrFeatures> qarBasicStandardAsrFeaturesList = new ArrayList<QualityQarBasicStandardAsrFeatures>();
		for (QualityAsrFeaturesBean qualityAsrFeaturesBean : asrFeaturesList) {
			QualityAsrFeaturesEntity innerData2 = qualityAsrFeaturesBean.getInnerData();
			QualityQarBasicStandardAsrFeatures qualityQarBasicStandardAsrFeatures = new QualityQarBasicStandardAsrFeatures();
			QualityQarBasicStandardAsrFeaturesEntity qualityQarBasicStandardAsrFeaturesEntity = new QualityQarBasicStandardAsrFeaturesEntity();
			qualityQarBasicStandardAsrFeatures.setInnerData(qualityQarBasicStandardAsrFeaturesEntity);
			qualityQarBasicStandardAsrFeatures.getInnerData().setAsrFeaturesId(innerData2.getId());
			qarBasicStandardAsrFeaturesList.add(qualityQarBasicStandardAsrFeatures);
		}
		List<QualityQarBasicStandardCheck> qarBasicStandardCheckList = qualityQarBasicStandard
				.getQarBasicStandardCheckList();

		List<QualityQarBasicStandardRequirement> qarBasicStandardRequirementList = qualityQarBasicStandard
				.getQarBasicStandardRequirementList();

		QueryWrapper<QualityQarBasicStandardEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("part_number", innerData.getPartNumber());
		queryWrapper.eq("model", innerData.getModel());
		queryWrapper.eq("material_type", innerData.getMaterialType());
		queryWrapper.eq("material_number", innerData.getMaterialNumber());
		List<QualityQarBasicStandardEntity> selectList = qualityQarBasicStandardDao.selectList(queryWrapper);
		if (qarBasicStandardCheckList.size() > 0) {
			innerData.setIfCheck("1");
		} else {
			innerData.setIfCheck("0");
		}
		int sum = 0;
		for (QualityQarBasicStandardRequirement qualityQarBasicStandardRequirement : qarBasicStandardRequirementList) {
			if (qualityQarBasicStandardRequirement.getInnerData().getRequirementName().equals("0")) {
				sum = sum + 1;
			}
		}
		if (sum > 0) {
			innerData.setIfTest("1");
		} else {
			innerData.setIfTest("0");
		}

		if (StringUtils.isEmpty(innerData.getStatus())) {
			innerData.setStatus("0");
		}
		// 当母本中不存在主键，说明时新增一个新的qar母本数据，而不是保存母本数据
		if (innerData.getId() == 0) {
			// 校验数据是否存在
			validateField(innerData, false);
			if (selectList.size() > 0) {
				throw new RuntimeException(
						"当前件号" + innerData.getPartNumber() + "=》当前型号" + innerData.getModel() + "=>物料类型=》"
								+ innerData.getMaterialType() + "=>物料编码=》" + innerData.getMaterialNumber() + "已存在！");
			}
			// 当存在计划代办数据时处理数据
			validatePlanToDoIfDeal(innerData.getPartNumber(), innerData.getPartName(), innerData.getMaterialNumber(),
					innerData.getMaterialType());
			innerData.setVersion(1);
			baseEntityDataUtil.setBaseEntityData(innerData);
			qualityQarBasicStandardDao.insert(innerData);
			// 新增传入的限售件数据
			List<BasicStandardRestrictedPart> restrictedPartList = qualityQarBasicStandard.getRestrictedPartList();
			if (restrictedPartList.size() > 0) {
				basicStandardRestrictedPartDataHandler.batchInsertData(qualityQarBasicStandard.getRestrictedPartList());
			}
		} else {
			// 校验数据是否存在
			validateField(innerData, true);
			// 当保存母本数据时
			// 检验升版数据中是否存在qar母本对应数据 当存在时，查询的数据以母本升版为主
			QueryWrapper<QualityQarBasicStandardUpgradeEntity> upgrade = new QueryWrapper<QualityQarBasicStandardUpgradeEntity>();
			upgrade.eq("row_status", 1);
			upgrade.eq("qar_basic_standard_id", innerData.getId());
			QualityQarBasicStandardUpgradeEntity selectOne = qualityQarBasicStandardUpgradeDao.selectOne(upgrade);
			innerData.setLevel(1);
			baseEntityDataUtil.updateBaseEntityData(innerData);
			if (selectOne != null) {
				// 应该修改母本中的数据
				// 给母本升版数据赋值
				QualityQarBasicStandardUpgrade qualityQarBasicStandardUpgrade = new QualityQarBasicStandardUpgrade();
				qualityQarBasicStandardUpgradeDataHandler.copyQarBasicStandardToUpgrade(qualityQarBasicStandard,
						qualityQarBasicStandardUpgrade);
				qualityQarBasicStandardUpgrade.getInnerData().setId(selectOne.getId());
				qualityQarBasicStandardUpgrade.getInnerData().setQarBasicStandardId(selectOne.getQarBasicStandardId());
				qualityQarBasicStandardUpgradeDao.updateById(qualityQarBasicStandardUpgrade.getInnerData());
				innerData.setId(selectOne.getId());
			} else {
				qualityQarBasicStandardDao.updateById(innerData);
			}

			// 当保存时，更新母本对应的限售件数据
			basicStandardRestrictedPartDataHandler
					.checkUpdateRestrictedPartData(qualityQarBasicStandard.getRestrictedPartList(), selectOne.getId());
		}
		// 新增qar母本
		long id = innerData.getId();

		if (qarBasicStandardAsrFeaturesList.size() > 0) {
			for (QualityQarBasicStandardAsrFeatures entity : qarBasicStandardAsrFeaturesList) {
				entity.getInnerData().setQarBasicStandardId(id);
			}
		}

		if (qarBasicStandardCheckList.size() > 0) {
			for (QualityQarBasicStandardCheck qualityQarBasicStandardCheck : qarBasicStandardCheckList) {
				qualityQarBasicStandardCheck.getInnerData().setQarBasicStandardId(id);
			}
		}

		if (qarBasicStandardRequirementList.size() > 0) {
			for (QualityQarBasicStandardRequirement qualityQarBasicStandardRequirement : qarBasicStandardRequirementList) {
				qualityQarBasicStandardRequirement.getInnerData().setQarBasicStandardId(id);
			}
		}

		// 批量删除asr特征库对应数据
		qualityQarBasicStandardAsrFeaturesDataHandler.removeDataByQarBasicStandardId(innerData.getId());
		if (qarBasicStandardAsrFeaturesList.size() > 0) {
			// 批量新增asr特征库对应数据
			qualityQarBasicStandardAsrFeaturesDataHandler
					.batchInsertQarBasicStandardAsrFeatures(qarBasicStandardAsrFeaturesList);
		}

		// 批量删除qar母本检验/验证特性
		qualityQarBasicStandardCheckDataHandler.removeDataByQarBasicStandardUpgradeId(innerData.getId());
		if (qarBasicStandardCheckList.size() > 0) {
			// 批量新增qar母本检验/验证特性
			qualityQarBasicStandardCheckDataHandler.batchInsertQarBasicStandardCheck(qarBasicStandardCheckList);
		}

		// 批量删除qar母本对应的检验/限制要求
		qualityQarBasicStandardRequirementDataHandler.removeByQarBasicStandardId(innerData.getId());

		if (qarBasicStandardRequirementList.size() > 0) {
			// 批量新增qar母本对应的检验/限制要求
			qualityQarBasicStandardRequirementDataHandler
					.batchInsertQarBasicStandardRequirement(qarBasicStandardRequirementList);
		}
		return resultBean;
	}

	/**
	 * 将母本的升版表中数据复制到母本
	 **/
	public void copyQarUpgradeToBasicStandard(QualityQarBasicStandardUpgradeEntity qualityQarBasicStandardUpgradeEntity,
			QualityQarBasicStandardEntity qualityQarBasicStandardEntity) {
		qualityQarBasicStandardEntity.setAtpNumber(qualityQarBasicStandardUpgradeEntity.getAtpNumber());
		qualityQarBasicStandardEntity.setCategory(qualityQarBasicStandardUpgradeEntity.getCategory());
		qualityQarBasicStandardEntity.setChangedLetters(qualityQarBasicStandardEntity.getChangedLetters());
		qualityQarBasicStandardEntity.setChangeNumber(qualityQarBasicStandardUpgradeEntity.getChangeNumber());
		qualityQarBasicStandardEntity.setColorCode(qualityQarBasicStandardUpgradeEntity.getColorCode());
		qualityQarBasicStandardEntity.setDrawingNumber(qualityQarBasicStandardUpgradeEntity.getDrawingNumber());
		qualityQarBasicStandardEntity.setDrawingRevision(qualityQarBasicStandardUpgradeEntity.getDrawingRevision());
		qualityQarBasicStandardEntity.setIfCheck(qualityQarBasicStandardUpgradeEntity.getIfCheck());
		qualityQarBasicStandardEntity.setIfCorrectEntrust(qualityQarBasicStandardUpgradeEntity.getIfCorrectEntrust());
		qualityQarBasicStandardEntity.setIfRestrictedPart(qualityQarBasicStandardUpgradeEntity.getIfRestrictedPart());
		qualityQarBasicStandardEntity.setIfSampling(qualityQarBasicStandardUpgradeEntity.getIfSampling());
		qualityQarBasicStandardEntity.setIfTest(qualityQarBasicStandardUpgradeEntity.getIfTest());
		qualityQarBasicStandardEntity.setLevel(qualityQarBasicStandardUpgradeEntity.getLevel());
		qualityQarBasicStandardEntity.setStatus(qualityQarBasicStandardUpgradeEntity.getStatus());
		qualityQarBasicStandardEntity.setStandard(qualityQarBasicStandardUpgradeEntity.getStandard());
		qualityQarBasicStandardEntity.setStandardVersion(qualityQarBasicStandardUpgradeEntity.getStandardVersion());
		qualityQarBasicStandardEntity
				.setProjectRequirements(qualityQarBasicStandardUpgradeEntity.getProjectRequirements());
		qualityQarBasicStandardEntity
				.setRestrictedPartRequirements(qualityQarBasicStandardUpgradeEntity.getRestrictedPartRequirements());
		qualityQarBasicStandardEntity
				.setRestrictedPartStorageTime(qualityQarBasicStandardUpgradeEntity.getRestrictedPartStorageTime());
		qualityQarBasicStandardEntity.setChangedLetters(qualityQarBasicStandardUpgradeEntity.getChangedLetters());
		qualityQarBasicStandardEntity
				.setRouteMaterialNumber(qualityQarBasicStandardUpgradeEntity.getRouteMaterialNumber());
		qualityQarBasicStandardEntity.setManufacturer(qualityQarBasicStandardUpgradeEntity.getManufacturer());
		qualityQarBasicStandardEntity.setMaterialNumber(qualityQarBasicStandardUpgradeEntity.getMaterialNumber());
		qualityQarBasicStandardEntity.setMaterialScience(qualityQarBasicStandardUpgradeEntity.getMaterialScience());
		qualityQarBasicStandardEntity.setMaterialType(qualityQarBasicStandardUpgradeEntity.getMaterialType());
		qualityQarBasicStandardEntity.setMatNumber(qualityQarBasicStandardUpgradeEntity.getMatNumber());
		qualityQarBasicStandardEntity.setModel(qualityQarBasicStandardUpgradeEntity.getModel());
		qualityQarBasicStandardEntity.setNorms(qualityQarBasicStandardUpgradeEntity.getNorms());
		qualityQarBasicStandardEntity.setPartName(qualityQarBasicStandardUpgradeEntity.getPartName());
		qualityQarBasicStandardEntity.setPartNumber(qualityQarBasicStandardUpgradeEntity.getPartNumber());
		qualityQarBasicStandardEntity
				.setPerformanceRequirement(qualityQarBasicStandardUpgradeEntity.getPerformanceRequirement());
		qualityQarBasicStandardEntity.setPlanRemark(qualityQarBasicStandardUpgradeEntity.getPlanRemark());
		qualityQarBasicStandardEntity.setId(qualityQarBasicStandardUpgradeEntity.getQarBasicStandardId());
		qualityQarBasicStandardEntity
				.setQarBasicStandardNumber(qualityQarBasicStandardUpgradeEntity.getQarBasicStandardNumber());
		qualityQarBasicStandardEntity.setRemark(qualityQarBasicStandardUpgradeEntity.getRemark());
		qualityQarBasicStandardEntity.setRequiredSize(qualityQarBasicStandardUpgradeEntity.getRequiredSize());
		qualityQarBasicStandardEntity
				.setRestrictedPartControlMode(qualityQarBasicStandardUpgradeEntity.getRestrictedPartControlMode());
		qualityQarBasicStandardEntity
				.setRouteMaterialNumber(qualityQarBasicStandardUpgradeEntity.getRouteMaterialNumber());
		qualityQarBasicStandardEntity.setSamplesQuantity(qualityQarBasicStandardUpgradeEntity.getSamplesQuantity());
		qualityQarBasicStandardEntity.setSamplesSize(qualityQarBasicStandardUpgradeEntity.getSamplesSize());
		qualityQarBasicStandardEntity.setShape(qualityQarBasicStandardUpgradeEntity.getShape());
		qualityQarBasicStandardEntity.setSoftwareNumber(qualityQarBasicStandardUpgradeEntity.getSoftwareNumber());
		qualityQarBasicStandardEntity.setSoftwareRevision(qualityQarBasicStandardUpgradeEntity.getSoftwareRevision());
		qualityQarBasicStandardEntity.setTestItemQuantity(qualityQarBasicStandardUpgradeEntity.getTestItemQuantity());
		qualityQarBasicStandardEntity.setType(qualityQarBasicStandardUpgradeEntity.getType());
		qualityQarBasicStandardEntity.setVersion(qualityQarBasicStandardUpgradeEntity.getVersion());
		qualityQarBasicStandardEntity
				.setIfChildRestrictedPart(qualityQarBasicStandardUpgradeEntity.getIfChildRestrictedPart());
		qualityQarBasicStandardEntity.setRestrictedPartNo(qualityQarBasicStandardUpgradeEntity.getRestrictedPartNo());
		qualityQarBasicStandardEntity
				.setRestrictedPartProductNo(qualityQarBasicStandardUpgradeEntity.getRestrictedPartProductNo());
		qualityQarBasicStandardEntity.setCompositionStyle(qualityQarBasicStandardUpgradeEntity.getCompositionStyle());
	}

	// 通过母本主键获取母本信息，当母本升版表中有数据时以升版表数据为准，当没有时以母本表为准
	public ResultBean selectByQarBasicStandardId(QualityQarBasicStandard qualityQarBasicStandard, Boolean flag) {
		QualityQarBasicStandard qualityQarBasicStandard2 = new QualityQarBasicStandard();
		ResultBean resultBean = new ResultBean(true);

		QualityQarBasicStandardEntity innerData = qualityQarBasicStandard.getInnerData();
		if (innerData.getId() == 0) {
			throw new RuntimeException("无法获取母本主键信息！");
		}
		long qarBasicStandardId = innerData.getId();

		// 通过主键id查询qar母本数据信息
		QualityQarBasicStandardEntity selectById = qualityQarBasicStandardDao.selectById(qarBasicStandardId);
		// 获取零件材料图号编码
		String partNumber = selectById.getPartNumber();

		// 检验升版数据中是否存在qar母本对应数据 当存在时，查询的数据以母本升版为主
		QueryWrapper<QualityQarBasicStandardUpgradeEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardUpgradeEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("qar_basic_standard_id", qarBasicStandardId);
		QualityQarBasicStandardUpgradeEntity selectOne = qualityQarBasicStandardUpgradeDao.selectOne(queryWrapper);
		// 当升版表中有数据时，查询升版对应主键，并且将升版数据赋值到表中
		if (selectOne != null && flag) {
			qarBasicStandardId = selectOne.getId();
			QualityQarBasicStandardEntity qualityQarBasicStandardEntity = new QualityQarBasicStandardEntity();
			// 复制升版表中数据到母本中
			copyQarUpgradeToBasicStandard(selectOne, qualityQarBasicStandardEntity);
			qualityQarBasicStandard2.setInnerData(qualityQarBasicStandardEntity);
		} else {
			qualityQarBasicStandard2.setInnerData(selectById);
		}

		// 通过qar母本主键id查询母本特征库的附属信息
		List<QualityAsrFeaturesBean> selectByQarBasicStandardId = qualityQarBasicStandardAsrFeaturesDataHandler
				.selectFeaturesByQarBasicStandardId(qarBasicStandardId, partNumber);
		qualityQarBasicStandard2.setQarBasicStandardAsrFeaturesList(selectByQarBasicStandardId);

		// 通过qar母本主键id查询母本实验的附属信息
		List<QualityQarBasicStandardRequirement> qualityQarBasicStandardRequirementList = qualityQarBasicStandardRequirementDataHandler
				.selectByQarBasicStandardId(qarBasicStandardId);
		qualityQarBasicStandard2.setQarBasicStandardRequirementList(qualityQarBasicStandardRequirementList);

		// 通过qar母本主键id查询母本上传照片的附属信息
		List<QualityQarBasicStandardCheck> selectByQarBasicStandardId2 = qualityQarBasicStandardCheckDataHandler
				.selectByQarBasicStandardId(qarBasicStandardId);
		qualityQarBasicStandard2.setQarBasicStandardCheckList(selectByQarBasicStandardId2);

		List<BasicStandardRestrictedPart> selectByBasicStandardId = basicStandardRestrictedPartDataHandler
				.selectByBasicStandardId(qarBasicStandardId);
		qualityQarBasicStandard2.setRestrictedPartList(selectByBasicStandardId);
		resultBean.setObject(qualityQarBasicStandard2);
		return resultBean;
	}

	// 通过母本主键删除对应数据信息及附属信息
	public ResultBean batchDeleteByQarBasicStandardIds(List<QualityQarBasicStandard> list) {
		ResultBean resultBean = new ResultBean(true);
		if (list.size() > 0) {
			List<Long> idsList = new ArrayList<Long>();
			List<QualityQarBasicStandardEntity> qarBasicStandardList = new ArrayList<QualityQarBasicStandardEntity>();
			for (QualityQarBasicStandard qualityQarBasicStandard : list) {
				QualityQarBasicStandardEntity innerData = qualityQarBasicStandard.getInnerData();
				QualityQarBasicStandardEntity selectById = qualityQarBasicStandardDao.selectById(innerData.getId());
				selectById.setRowStatus(0);
				baseEntityDataUtil.updateBaseEntityData(selectById);
				idsList.add(selectById.getId());
				qarBasicStandardList.add(selectById);
			}
			// 删除母本表中的数据
			updateBatchById(qarBasicStandardList, qarBasicStandardList.size());

			// 删除asr特征库对应数据通过母本主键集合
			qualityQarBasicStandardAsrFeaturesDataHandler.batchDeleteByQarBasicStandardId(idsList);

			// 删除实验数据
			qualityQarBasicStandardRequirementDataHandler.batchDeleteByQarBasicStandardIds(idsList);

			// 删除检验/验证特征信息
			qualityQarBasicStandardCheckDataHandler.batchDeleteByQarBasicStandardIds(idsList);

		} else {
			resultBean.setErrorMessge("无选中数据，删除失败！");
		}
		return resultBean;
	}

	// 母本升版功能
	public ResultBean qarBasicStandardUpgrade(QualityQarBasicStandard qualityQarBasicStandard) throws RuntimeException {
		String ststus = qualityQarBasicStandard.getInnerData().getStatus();
		// 当母本在升版中时
		if ("1".equals(ststus)) {
			qualityQarBasicStandard = (QualityQarBasicStandard) this
					.selectByQarBasicStandardId(qualityQarBasicStandard, true).getObject();
		}
		qualityQarBasicStandard.getInnerData().setStatus(ststus);
		ResultBean resultBean = new ResultBean(true);
		QualityQarBasicStandardEntity innerData = qualityQarBasicStandard.getInnerData();
		// 查询母本对应的数据
//		
		// 查询qar母版对应数据
		QueryWrapper<QualityQarBasicStandardEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("qar_basic_standard_id", innerData.getId());
		QualityQarBasicStandardEntity selectOne = qualityQarBasicStandardDao.selectOne(queryWrapper);
		baseEntityDataUtil.updateBaseEntityData(selectOne);

		// 如果是升版状态则改为升版中
		if (innerData.getStatus().equals("1")) {
			selectOne.setStatus("1");
			// 更新qar母版状态
			qualityQarBasicStandardDao.updateById(selectOne);
			// 当为升版中时新增一个母本升版提醒数据
			saveQarPlanToDo(selectOne);
			// 保存升版数据
			qualityQarBasicStandardUpgradeDataHandler.insertQarBasicStandardUpgradeData(qualityQarBasicStandard);
			// 冻结全部计划中和检验中的asr检验单
			this.freezeAllAsrCheckForm(innerData.getId(), "1");
			// 冻结qar检验单
			qualityQarCheckInvoiceDataHandler.updateCurrentStatus(innerData.getId(),
					MomConstants.QUALITY_QAR_CURRENT_STATUS_FROZEN);
		} else if (innerData.getStatus().equals("2")) {
			// 当检验特征有改动时新增任务代办中消息提醒
			insertTaskPendingMessageByQarBasicStandardId(qualityQarBasicStandard.getQarBasicStandardCheckList(),
					selectOne.getId());
			// 当实验单据数据有变化时，新增任务代办中消息提醒
			insertPendingMessageBystandardRequirement(qualityQarBasicStandard.getQarBasicStandardRequirementList(),
					selectOne);
			// 如果是升版的提交 状态为启用,版本加1
			selectOne.setStatus("2");
			qualityQarBasicStandardDao.updateById(selectOne);
			qualityQarBasicStandardUpgradeDataHandler.submitQarBasicStandardUpgradeData(qualityQarBasicStandard);

		}
		return resultBean;
	}

	// 当实验数据有变化新增计划代办中的
	public void insertPendingMessageBystandardRequirement(List<QualityQarBasicStandardRequirement> list,
			QualityQarBasicStandardEntity standardEntity) {
		if (CollectionUtils.isEmpty(list)) {
			list = new ArrayList<QualityQarBasicStandardRequirement>();
		}
		List<QualityQarBasicStandardRequirementEntity> addList = new ArrayList<QualityQarBasicStandardRequirementEntity>();
		List<QualityQarBasicStandardRequirementEntity> deleteList = new ArrayList<QualityQarBasicStandardRequirementEntity>();
		// 过滤实验单据数据
		List<QualityQarBasicStandardRequirement> StandardRequirementList = list.stream().filter(item -> (item.getInnerData().getRequirementType()).equals(MomConstants.QUALITY_QAR_REQUIREMENT_TYPE_TEST)).collect(Collectors.toList());
		if (!CollectionUtils.isEmpty(StandardRequirementList)) {
			// 获取实验单据实体集合
			List<QualityQarBasicStandardRequirementEntity> entityList = StandardRequirementList.stream()
					.map(QualityQarBasicStandardRequirement::getInnerData).collect(Collectors.toList());
			List<QualityQarBasicStandardRequirement> selectByQarBasicStandardId = qualityQarBasicStandardRequirementDataHandler
					.selectByQarBasicStandardIdAndType(standardEntity.getId(),MomConstants.QUALITY_QAR_REQUIREMENT_TYPE_TEST);
			List<QualityQarBasicStandardRequirementEntity> selectStandardRequirementEntityList = selectByQarBasicStandardId
					.stream().filter(item -> item.getInnerData() != null).map(item -> item.getInnerData())
					.collect(Collectors.toList());
			addList = entityList.stream().filter(item -> !selectStandardRequirementEntityList.contains(item))
					.collect(Collectors.toList());
			deleteList = selectStandardRequirementEntityList.stream().filter(item -> !entityList.contains(item))
					.collect(Collectors.toList());
			List<QualityQarTaskPendingMessageEntity> pendingMessageByTestData = qualityQarTaskPendingMessageDataHandler
					.getPendingMessageByTestData(addList, "新增实验数据", standardEntity);
			pendingMessageByTestData.forEach(item ->baseEntityDataUtil.setBaseEntityData(item));
			List<QualityQarTaskPendingMessageEntity> pendingMessageByTestData2 = qualityQarTaskPendingMessageDataHandler
					.getPendingMessageByTestData(deleteList, "删除实验数据", standardEntity);
			pendingMessageByTestData2.forEach(item -> baseEntityDataUtil.setBaseEntityData(item));
			pendingMessageByTestData.addAll(pendingMessageByTestData2);
			qualityQarTaskPendingMessageDataHandler.saveBatch(pendingMessageByTestData,
					pendingMessageByTestData.size());
		}
	}

	// 保存qar母本升版提醒的数据
	public void saveQarPlanToDo(QualityQarBasicStandardEntity selectOne) {
		// 当母本升版时升版母本在qar任务查询的母本升版中没有信息时
		QueryWrapper<QualityPlanToDoEntity> queryWrapper2 = new QueryWrapper<QualityPlanToDoEntity>();
		queryWrapper2.eq("row_status", 1);
		queryWrapper2.eq("qar_basic_standard_number", selectOne.getQarBasicStandardNumber());
		QualityPlanToDoEntity selectOne2 = qualityPlanToDoDao.selectOne(queryWrapper2);
		if (selectOne2 != null) {
			// 当母本的状态为升版中时,保存一条qar代办信息
			QualityPlanToDoEntity qualityPlanToDoEntity = new QualityPlanToDoEntity();
			qualityPlanToDoEntity.setLevel(selectOne.getLevel() + 1);
			qualityPlanToDoEntity.setMaterialNumber(selectOne.getMaterialNumber());
			qualityPlanToDoEntity.setPartName(selectOne.getPartName());
			qualityPlanToDoEntity.setPartNo(selectOne.getPartNumber());
			qualityPlanToDoEntity.setQarBasicStandardNumber(selectOne.getQarBasicStandardNumber());
			qualityPlanToDoEntity.setToDoType(3);
			qualityPlanToDoEntity.setToDoContent("母本升版中");
			baseEntityDataUtil.setBaseEntityData(qualityPlanToDoEntity);
			qualityPlanToDoDao.insert(qualityPlanToDoEntity);
		}
	}

	// 取消升版功能
	public ResultBean cancelQarBasicStandardUpgrade(QualityQarBasicStandard qualityQarBasicStandard) {
		ResultBean resultBean = new ResultBean(true);
		long id = qualityQarBasicStandard.getInnerData().getId();
		QueryWrapper<QualityQarBasicStandardUpgradeEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardUpgradeEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("qar_basic_standard_id", id);
		QualityQarBasicStandardUpgradeEntity selectOne = qualityQarBasicStandardUpgradeDao.selectOne(queryWrapper);
		if (selectOne != null) {
			long UpgradeId = selectOne.getId();
			// 逻辑删除升版主键
			baseEntityDataUtil.updateBaseEntityData(selectOne);
			selectOne.setRowStatus(0);
			qualityQarBasicStandardUpgradeDao.updateById(selectOne);
			// 查询qar母版对应数据
			QueryWrapper<QualityQarBasicStandardEntity> queryWrapper1 = new QueryWrapper<QualityQarBasicStandardEntity>();
			queryWrapper1.eq("row_status", 1);
			queryWrapper1.eq("qar_basic_standard_id", id);
			QualityQarBasicStandardEntity selectOne1 = qualityQarBasicStandardDao.selectOne(queryWrapper1);
			baseEntityDataUtil.updateBaseEntityData(selectOne1);
			// 更新对应qar母本状态为启用
			selectOne1.setStatus("2");
			selectOne1.setRowStatus(1);
			qualityQarBasicStandardDao.updateById(selectOne1);
		}
		// 解冻全部计划中和检验中的asr检验单
		this.freezeAllAsrCheckForm(id, MomConstants.QUALITY_QAR_CURRENT_STATUS_UNFROZEN);
		// 解冻Qar
		qualityQarCheckInvoiceDataHandler.updateCurrentStatus(id, MomConstants.QUALITY_QAR_CURRENT_STATUS_UNFROZEN);
		return resultBean;
	}

	// 分页查询qar母本对应数据
	public ResultBean selectBySomeFields(@RequestBody QualityQarBasicStandard qualityQarBasicStandard) {
		ResultBean resultBean = new ResultBean(true);
		if (qualityQarBasicStandard.getPageNum() == 0) {
			qualityQarBasicStandard.setPageNum(1);
		}
		if (qualityQarBasicStandard.getPageSize() == 0) {
			qualityQarBasicStandard.setPageSize(10);
		}
		QualityQarBasicStandardEntity innerData = qualityQarBasicStandard.getInnerData();
		Page<QualityQarBasicStandardEntity> page = new Page<QualityQarBasicStandardEntity>(
				qualityQarBasicStandard.getPageNum(), qualityQarBasicStandard.getPageSize(), true);
		QueryWrapper<QualityQarBasicStandardEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardEntity>();
		queryWrapper.eq("row_status", 1);
		if (StringUtils.isNotEmpty(innerData.getPartName())) {
			queryWrapper.like("part_name", innerData.getPartName());
		}
		if (StringUtils.isNotEmpty(innerData.getPartNumber())) {
			queryWrapper.like("part_number", innerData.getPartNumber());
		}
		if (StringUtils.isNotEmpty(innerData.getMaterialNumber())) {
			queryWrapper.like("material_number", innerData.getMaterialNumber());
		}
		if (StringUtils.isNotEmpty(innerData.getStatus())) {
			queryWrapper.eq("status", innerData.getStatus());
		}
		if (StringUtils.isNotEmpty(innerData.getModel())) {
			queryWrapper.eq("model", innerData.getModel());
		}
		if (StringUtils.isNotEmpty(innerData.getMaterialScience())) {
			queryWrapper.like("material_science", innerData.getMaterialScience());
		}
		if (innerData.getCreationStartTime() != null) {
			queryWrapper.like("creation_time", innerData.getCreationStartTime());
		}
		if (innerData.getCreationEndTime() != null) {
			queryWrapper.like("creation_time", innerData.getCreationEndTime());
		}
		if (StringUtils.isNotEmpty(innerData.getIfCheck())) {
			queryWrapper.like("if_check", innerData.getIfCheck());
		}
		if (StringUtils.isNotEmpty(innerData.getIfCorrectEntrust())) {
			queryWrapper.like("if_correct_entrust", innerData.getIfCorrectEntrust());
		}
		IPage<QualityQarBasicStandardEntity> selectPage = qualityQarBasicStandardDao.selectPage(page, queryWrapper);
		@SuppressWarnings("unchecked")
		LimitPageBean<QualityQarBasicStandardEntity> of = (LimitPageBean<QualityQarBasicStandardEntity>) LimitPageBean
				.of(selectPage);
		resultBean.setObject(of);
		return resultBean;
	}

	public QualityQarBasicStandard selectById(long id) {
		QualityQarBasicStandardEntity selectById = qualityQarBasicStandardDao.selectById(id);
		QualityQarBasicStandard qualityQarBasicStandard = new QualityQarBasicStandard();
		qualityQarBasicStandard.setInnerData(selectById);
		return qualityQarBasicStandard;
	}

	public List<QualityQarBasicStandardEntity> selectByTypeIsJizai() {
		QueryWrapper<QualityQarBasicStandardEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("material_status", DataStatus.jiZaiXiTong);
		List<QualityQarBasicStandardEntity> selectList = qualityQarBasicStandardDao.selectList(queryWrapper);
		return selectList;
	}

	// 新增任务代办时的信息提示www
	public ResultBean insertTaskPendingMessageByQarBasicStandardId(List<QualityQarBasicStandardCheck> list,
			long QarBasicStandardId) {
		ResultBean resultBean = new ResultBean(true);
		// 通过qar母本主键查询对应验证特性信息
		List<QualityQarBasicStandardCheck> selectCheckMainByBasicStandardCheckId = qualityQarBasicStandardCheckDataHandler
				.selectCheckMainByBasicStandardCheckId(QarBasicStandardId);
		// 通过母本主键获取母本信息
		QualityQarBasicStandardEntity qarBasicStandardEntity = qualityQarBasicStandardDao
				.selectById(QarBasicStandardId);

		// 需要新增的数据集合
		List<QualityQarBasicStandardCheckEntity> addCheckEntityList = new ArrayList<QualityQarBasicStandardCheckEntity>();
		List<QualityQarBasicStandardCheckEntity> deleteCheckEntityList = new ArrayList<QualityQarBasicStandardCheckEntity>();
		// 找出要新增的特征数据
		for (QualityQarBasicStandardCheck qualityQarBasicStandardCheck : list) {
			List<String> collect = selectCheckMainByBasicStandardCheckId.stream()
					.map(item -> item.getInnerData().getCheckItem()).collect(Collectors.toList());
			// 当存在相同父项目时
			String checkItem = qualityQarBasicStandardCheck.getInnerData().getCheckItem();
			if (collect.contains(checkItem)) {
				List<QualityQarBasicStandardCheck> collect2 = selectCheckMainByBasicStandardCheckId.stream()
						.filter(item -> item.getInnerData().getCheckItem().equals(checkItem))
						.collect(Collectors.toList());

				List<QualityQarBasicStandardCheckEntity> qarBasicStandardCheckList2 = qualityQarBasicStandardCheck
						.getQarBasicStandardCheckList();
				// 查询传入子项集合
				List<QualityQarBasicStandardCheckEntity> qarBasicStandardCheckList = collect2.get(0)
						.getQarBasicStandardCheckList();// 新增项集合
//				List<QualityQarBasicStandardCheckEntity> collect3 = qarBasicStandardCheckList2.stream().filter(item -> !qarBasicStandardCheckList.contains(item)).collect(Collectors.toList());
				List<String> addCheckDetil = qarBasicStandardCheckList2.stream().map(item -> item.getCheckDetail())
						.filter(item -> item != null).collect(Collectors.toList());
				List<String> selectCheckDetil = qarBasicStandardCheckList.stream().map(item -> item.getCheckDetail())
						.filter(item -> item != null).collect(Collectors.toList());
				List<String> add = addCheckDetil.stream().filter(item -> !selectCheckDetil.contains(item))
						.collect(Collectors.toList());
				if (!CollectionUtils.isEmpty(add)) {
					for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : qarBasicStandardCheckList2) {
						for (String detail : add) {
							if (qualityQarBasicStandardCheckEntity.getCheckDetail().equals(detail)) {
								addCheckEntityList.add(qualityQarBasicStandardCheckEntity);
								break;
							}
						}
					}
				}
			} else {
				// 当新增父项目在查询表中不存在
				addCheckEntityList.add(qualityQarBasicStandardCheck.getInnerData());
				List<QualityQarBasicStandardCheckEntity> qarBasicStandardCheckList = qualityQarBasicStandardCheck
						.getQarBasicStandardCheckList();
				if (!CollectionUtils.isEmpty(qarBasicStandardCheckList)) {
					addCheckEntityList.addAll(qarBasicStandardCheckList);
				}
			}
		}

		// 找出要刪除的特征数据
		for (QualityQarBasicStandardCheck qualityQarBasicStandardCheck : selectCheckMainByBasicStandardCheckId) {
			List<String> collect = list.stream().map(item -> item.getInnerData().getCheckItem())
					.collect(Collectors.toList());
			// 当存在相同父项目时
			String checkItem = qualityQarBasicStandardCheck.getInnerData().getCheckItem();
			if (collect.contains(checkItem)) {
				List<QualityQarBasicStandardCheck> collect2 = list.stream()
						.filter(item -> item.getInnerData().getCheckItem().equals(checkItem))
						.collect(Collectors.toList());
				// 新增项集合
				List<QualityQarBasicStandardCheckEntity> qarBasicStandardCheckList2 = qualityQarBasicStandardCheck
						.getQarBasicStandardCheckList();
				// 查询项集合
				List<QualityQarBasicStandardCheckEntity> qarBasicStandardCheckList = collect2.get(0)
						.getQarBasicStandardCheckList();
				// 新增的detail集合
				List<String> addDetail = qarBasicStandardCheckList2.stream().map(item -> item.getCheckDetail()).collect(Collectors.toList());
				// 查询的detail集合
				List<String> selectDetail = qarBasicStandardCheckList.stream().map(item -> item.getCheckDetail()).collect(Collectors.toList());
				
				List<String> collect3 = selectDetail.stream()
						.filter(item -> !addDetail.contains(item)).collect(Collectors.toList());
				if (!CollectionUtils.isEmpty(collect3)) {
					for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : deleteCheckEntityList) {
						for (String detail : collect3) {
							if (qualityQarBasicStandardCheckEntity.getCheckDetail().equals(detail)) {
								deleteCheckEntityList.add(qualityQarBasicStandardCheckEntity);
								break;
							}
						}
					}
				}
			} else {
				// 当查詢父项目在新增表中不存在
				deleteCheckEntityList.add(qualityQarBasicStandardCheck.getInnerData());
				List<QualityQarBasicStandardCheckEntity> qarBasicStandardCheckList = qualityQarBasicStandardCheck
						.getQarBasicStandardCheckList();
				if (!CollectionUtils.isEmpty(qarBasicStandardCheckList)) {
					deleteCheckEntityList.addAll(qarBasicStandardCheckList);
				}
			}
		}

		List<QualityQarTaskPendingMessageEntity> pendingMessageList = new ArrayList<QualityQarTaskPendingMessageEntity>();
		if (addCheckEntityList.size() > 0) {
			for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : addCheckEntityList) {
				QualityQarTaskPendingMessageEntity qualityQarTaskPendingMessageEntity = new QualityQarTaskPendingMessageEntity();
				if (StringUtils.isEmpty(qualityQarBasicStandardCheckEntity.getCheckItem())) {
					qualityQarTaskPendingMessageEntity
							.setContent("新增检验/验证特性项目详情：" + qualityQarBasicStandardCheckEntity.getCheckDetail());
				} else {
					qualityQarTaskPendingMessageEntity
							.setContent("新增检验/验证特性项目：" + qualityQarBasicStandardCheckEntity.getCheckItem());
				}
				qualityQarTaskPendingMessageEntity.setLevel(qarBasicStandardEntity.getVersion());
				qualityQarTaskPendingMessageEntity.setPartName(qarBasicStandardEntity.getPartName());
				qualityQarTaskPendingMessageEntity.setPartNumber(qarBasicStandardEntity.getPartNumber());
				qualityQarTaskPendingMessageEntity.setQarBasicStandardId(qarBasicStandardEntity.getId());
				baseEntityDataUtil.setBaseEntityData(qualityQarTaskPendingMessageEntity);
				pendingMessageList.add(qualityQarTaskPendingMessageEntity);
			}
		}
		if (deleteCheckEntityList.size() > 0) {
			for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : deleteCheckEntityList) {
				QualityQarTaskPendingMessageEntity qualityQarTaskPendingMessageEntity = new QualityQarTaskPendingMessageEntity();
				if (StringUtils.isEmpty(qualityQarBasicStandardCheckEntity.getCheckItem())) {
					qualityQarTaskPendingMessageEntity
							.setContent("删除检验/验证特性项目详情：" + qualityQarBasicStandardCheckEntity.getCheckDetail());
				} else {
					qualityQarTaskPendingMessageEntity
							.setContent("删除检验/验证特性项目：" + qualityQarBasicStandardCheckEntity.getCheckItem());
				}
				qualityQarTaskPendingMessageEntity.setLevel(qarBasicStandardEntity.getVersion());
				qualityQarTaskPendingMessageEntity.setPartName(qarBasicStandardEntity.getPartName());
				qualityQarTaskPendingMessageEntity.setPartNumber(qarBasicStandardEntity.getPartNumber());
				qualityQarTaskPendingMessageEntity.setQarBasicStandardId(qarBasicStandardEntity.getId());
				qualityQarTaskPendingMessageEntity
						.setQarBasicStandardNumber(qarBasicStandardEntity.getQarBasicStandardNumber());
				baseEntityDataUtil.setBaseEntityData(qualityQarTaskPendingMessageEntity);
				pendingMessageList.add(qualityQarTaskPendingMessageEntity);
			}
		}
		qualityQarTaskPendingMessageDataHandler.saveBatch(pendingMessageList, pendingMessageList.size());
		return resultBean;
	}

	public List<Long> freezeAllAsrCheckForm(long qarBasicStandardId, String freeze) {
		// 通过母本查询检验单信息
		List<Long> ids = qualityQarBasicStandardDao.queryAsrCheckFormInfo(qarBasicStandardId);
		// 冻结这些检验单
		if (ids != null && ids.size() > 0) {
			qualityQarBasicStandardDao.updateAsrCheckFormFreezeById(freeze, ids);
		}
		return ids;
	}

}
